package com.thinkcms.service.service.seo;

import com.thinkcms.service.api.content.ContentAttributeService;
import com.thinkcms.service.api.content.ContentService;
import com.thinkcms.service.api.seo.SeoService;
import com.thinkcms.service.dto.content.ContentAttributeDto;
import com.thinkcms.service.dto.content.ContentDto;
import com.thinkcms.core.config.ThinkCmsConfig;
import com.thinkcms.core.constants.Constants;
import com.thinkcms.core.utils.ApiResult;
import com.thinkcms.core.utils.Checker;
import com.thinkcms.seo.seo.core.baidu.BaiDuEngine;
import com.thinkcms.seo.seo.core.word.WordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 内容 服务实现类
 * </p>
 *
 * @author LG
 * @since 2019-10-30
 */
@Slf4j
@Service
public class SeoServiceImpl  implements SeoService {

    @Autowired
    ContentAttributeService contentAttributeService;

    @Autowired
    ContentService contentService;

    @Autowired
    ThinkCmsConfig thinkCmsConfig;

    @Override
    public List<String> extractKeywordByContentId(String contentId) {
        List<String> keyWords= new ArrayList<>(16);
        ContentAttributeDto attributeDto= contentAttributeService.getByField("content_id",contentId);
        if(Checker.BeNotNull(attributeDto)){
            keyWords= WordUtil.extractKeyword(attributeDto.getText(),5);
        }
        return keyWords;
    }

    @Override
    public List<String> extractKeywordByContent(String content) {
        List<String> keyWords= new ArrayList<>(16);
        if(Checker.BeNotBlank(content)){
            keyWords= WordUtil.extractKeyword(content,5);
        }
        return keyWords;
    }

    @Override
    public ApiResult getFileContentByPath(String path) {
        if(Checker.BeNotBlank(path)){
            File file = new File(path);
            try {
                if (file.isFile()) {
                    String fileContent = FileUtils.readFileToString(file, Constants.DEFAULT_CHARSET_NAME);
                    return ApiResult.result(fileContent);
                }
            } catch (IOException e) {
                log.error("读取模板文件失败！");
                return null;
            }
        }
        return null;
    }

    @Override
    public ApiResult analysisContent(String id) {
        Integer star =5;
        Map<String,Object> analysisRes = new HashMap<>(16);
        List<String> keyWords = null; // 关键字
        ContentDto contentDto = contentService.getByPk(id);
        ContentAttributeDto attributeDto= contentAttributeService.getByField("content_id",id);
        if(Checker.BeNotNull(attributeDto)){
            keyWords= extractKeywordByContent(attributeDto.getText());
            analysisRes.put("remark",keyWords);
        }
        if(Checker.BeNotBlank(contentDto.getUrl())){
            String domainFullPath = thinkCmsConfig.getSiteDomain()+contentDto.getUrl();
            String fileFullPath = thinkCmsConfig.getSiteStaticFileRootPath()+contentDto.getUrl();
            Map<String,Boolean> recordMap= BaiDuEngine.isRecord(domainFullPath);
            analysisRes.put("record",recordMap);
            if(!recordMap.get("ok")){
                star -= 1;
            }
            analysisHtmlFile(fileFullPath,analysisRes,  star);
        }
        return ApiResult.result(analysisRes);
    }

    private void analysisHtmlFile(String filePath,Map<String,Object> analysisRes,Integer star){
        ApiResult apiResult=getFileContentByPath(filePath);
        if(Checker.BeNotNull(apiResult) && Checker.BeNotNull(apiResult.get("res"))){
            String html  =apiResult.get("res").toString();
            Document doc = Jsoup.parse(html);
            star=ckHtmlTitle(doc, analysisRes,star);
            star=ckHtmlMeta(doc, analysisRes,star);
            star=ckHtmlScript(doc, analysisRes,star);
            analysisRes.put("star",star);
        }
    }

    private Integer ckHtmlTitle(Document doc,Map<String,Object> analysisRes,Integer star){
        Elements element=doc.getElementsByTag("title");
        if(element.isEmpty()){
            star-=1;
            analysisRes.put("title","<span style='color:red'>页面没有标题,强烈建议新增标题title!</span>");
        }else{
            if(!element.hasText()){
                star-=1;
                analysisRes.put("title","<span style='color:red'>页面没有标题,强烈建议新增标题title!</span>");
            }else{
                analysisRes.put("title","<span style='color:green'>"+element.html()+"</span>");
            }
        }
        return  star;
    }

    private Integer ckHtmlScript(Document doc,Map<String,Object> analysisRes,Integer star){
        Elements element=doc.getElementsByTag("script");
        if(!element.isEmpty()){
            boolean hasScript =false;
            for(Element e :element){
                if(Checker.BeNotBlank(e.html())){
                    hasScript = true;
                }
            }
            if(hasScript){
                star-=1;
                analysisRes.put("script","<span style='color:red'>页面包含脚本代码建议封装js文件后单独引入!</span>");
            }else{
                analysisRes.put("script","<span style='color:green'>检测正常!</span>");
            }
        }
        return  star;
    }

    private Integer ckHtmlMeta(Document doc,Map<String,Object> analysisRes,Integer star){
        Elements keyElement=doc.select("meta[name=keywords]");
        if(keyElement.isEmpty()){
            star-=1;
            analysisRes.put("keyWords","<span style='color:red'>页面没有关键字,强烈建议新增关键字keyWords!</span>");
        }else{
            String keyWords=keyElement.get(0).attr("content");
            if(Checker.BeBlank(keyWords)){
                star-=1;
                analysisRes.put("keyWords","<span style='color:red'>页面没有关键字,强烈建议新增关键字keyWords!</span>");
            }else{
                analysisRes.put("keyWords","<span style='color:green'>"+keyWords+"</span>");
            }
        }

        Elements descElement=doc.select("meta[name=description]");
        if(descElement.isEmpty()){
            star-=1;
            analysisRes.put("description","<span style='color:red'>页面没有描述,强烈建议新增描述description!</span>");
        }else{
            String description=descElement.get(0).attr("content");
            if(Checker.BeBlank(description)){
                star-=1;
                analysisRes.put("description","<span style='color:red'>页面没有描述,强烈建议新增描述description!</span>");
            }else{
                analysisRes.put("description","<span style='color:green'>"+description+"</span>");
            }
        }
        return  star;
    }


}
